<?php
namespace App\Http\Controllers\Backstage;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Validator\AchievementVali;
use App\Http\Controllers\Validator\RoomInfoVail;
use App\Model\Account\SystemType;
use App\Model\Account\Type;
use App\Model\Backstage\Customers;
use App\Model\Backstage\RoomFollow;
use App\Model\Backstage\RoomInfo;
use App\Model\Backstage\RoomWordbook;
use App\Model\Backstage\RoomWordbookInfo;
use App\Model\Backstage\User;
use App\Tool\Error;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redis;
use Validator;
use Illuminate\Support\Facades\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth as qiniuAuth;
// 制定允许其他域名访问
header("Access-Control-Allow-Origin:*");
// 响应类型
header('Access-Control-Allow-Methods:GET, POST');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with, content-type');



/**
 * Class RoomInfoController
 * @package App\Http\Controllers\Backstage
 * 房源信息控制器
 * date:2018-4-29
 */
class RoomInfoController extends Controller
{
    private $arr = ['JPG', 'JPEG', 'PNG', 'GIF', 'jpg', 'jpeg', 'png', 'gif'];//PC APP端上传房源图片定义的格式
    private $size = 21000000;//PC APP上传图片限制的大小
    /**
     * 打开房源列表之前  检索条件里面的类型
     */
    public function getListType()
    {
//        $area_list = DB::table('area')->where(['parentId' => $this->city_code])->get();
        $branch_info = Auth::user();
        $data = [
            'province_code'     => $this->province_code,//省code
            'city_code'         => $this->city_code,//市code
            'city_name'         => $this->city,//市名字
            'area_name'         => DB::table('account_number_manager')->where('anm_id', Auth::user()['u_b_id'])->value('anm_area'),//区名字
            'store_id'          => $branch_info['u_d_id'],//部门ID
            'uid'               => $branch_info['u_id'],//用户ID
            'lastday'           => date('Y-m-d',strtotime('-1 month')),//上个月时间
            'day'               => date('Y-m-d',time()),//当天时间
//            'area_list'         => $area_list,//区县下拉框
        ];
        $data['optimal'] =  SystemType::storageRedis(27); //优选度
        $data['use'] =  SystemType::storageRedis(1); //用途
        $data['status'] =  SystemType::storageRedis(96); //状态
        $data['roomtype'] =  SystemType::storageRedis(40);//房型
        $data['numlayers'] =  SystemType::storageRedis(219);//层数
        $data['oriented'] =  SystemType::storageRedis(81);//朝向
        /**
         * 类型
         */
        //《住宅、商住、其他》--- 类型 204
        $data['zsq_type'] =  SystemType::storageRedis(204);

        //《商铺  铺厂 网点》----类型 237
        $data['spw_type'] =  SystemType::storageRedis(237);

        //《写字楼  写厂》-----类型  277
        $data['xx_type'] =  SystemType::storageRedis(277);

        //厂房 仓库-----类型  362
        $data['cc_type'] =  SystemType::storageRedis(362);

        //地皮-----类型  369
        $data['dp_type'] =  SystemType::storageRedis(369);

        //车位---------类型  394
        $data['c_type'] =  SystemType::storageRedis(394);


        return $this->success('ok', $data);
    }
    /**
     * 房源列表
     * Wu Ning
     */
    public function houseList (Request $request,RoomInfo $roomInfo, RoomWordbook $roomWordbook)
    {
        //房源状态等于1 未删除房源
        $where[] = ['room_status',1];
        $param = $request->all();

        //楼盘字典
        if($request->input('building_id')){
            $bId = $roomWordbook->getRoomId($param['building_id']);
            if (!$bId) {
                return $this->error(Error::NO_PROPERTY);
            }
            $where[] = ['building_id' , $bId];
        }

        //房型   普通房  优质房
        if($request->input('type_of_house_sale')){
            $where[] = ['type_of_house_sale' , $param['type_of_house_sale']];
        }
        //用途
        if($request->input('use_type')){
            $where[] = ['use_type' , $param['use_type']];
        }

        //面积
        if($request->input('r_acreage_begin')){   //开始面积
            $where[] = ['r_acreage', '>=', $param['r_acreage_begin']];
        }
        if($request->input('r_acreage_end')){   //结束面积
            $where[] = ['r_acreage', '<=', $param['r_acreage_end']];
        }

        //状态 有效 预定  已售3.已租4.我售5.我租6.暂缓7.未知
        if($request->input('status')){
            $where[] = ['status' , $param['status']];
        }

        //楼层
        if($request->input('floor_begin')){  //开始楼层
            $where[] = ['floor', '>=', $param['floor_begin']];
        }
        if($request->input('floor_end')){    //结束楼层
            $where[] = ['floor', '<=', $param['floor_end']];
        }
        //部门
        if ($request->input('r_d_id')){
            $where[] = ['r_d_id',$param['r_d_id']];
        } elseif (Auth::user()['u_d_id']) {
            $where[] = ['r_d_id',Auth::user()['u_d_id']];
        }else {
            $apptoken = $param['apptoken'];
            $data = explode(',', Redis::get($apptoken));
            $store_id  = $data[0];   //部门id
            $where[] = ['r_d_id', $store_id];
        }
        //员工
        if($request->input('source_uid')){
            $where[] = ['source_uid', $param['source_uid']];
        } elseif (!$request->input('r_d_id') && !$request->input('source_uid') && Auth::user()['u_id']) {
            $where[] = ['source_uid',Auth::user()['u_id']];
        } elseif (!$request->input('r_d_id') && !$request->input('source_uid') && !Auth::user()['u_id']) {
            $apptoken = $param['apptoken'];
            $data = explode(',', Redis::get($apptoken));
            $uid  = $data[2];   //员工ID
            $where[] = ['source_uid', $uid];
        }
        //交易类型  1 出售93  售低价最小值--最大值    2 出租94  租低价 最小值----最大值
        if($request->input('trading_type')){
            if ($request->input('trading_type') == 1 ) {
                $where[] = ['trading_type', '<>', 94];//类型 出售和租售
                if($request->input('small_price')){
                    $where[] = ['price', '>=', $param['small_price']];
                }
                if($request->input('big_price')){
                    $where[] = ['price', '<=', $param['big_price']];
                }
            }
            if ($request->input('trading_type') == 2 ) {
                $where[] = ['trading_type', '<>', 93];//类型 出租和租售
                if($request->input('small_price')){
                    $where[] = ['rents', '>=', $param['small_price']];
                }
                if($request->input('big_price')){
                    $where[] = ['rents', '<=', $param['big_price']];
                }
            }
        }
        //刚进列表  默认查询  录入时间  一个月之内的数据
        if (!$request->input('date_type')) {
            $where[] = ['r_created_at', '>=', strtotime(date('Y-m-d',strtotime('-1 month')).' 00:00:00')];
            $where[] = ['r_created_at', '<=', time()];
        }
        //录入时间
        if ($request->input('date_type') == 1){
            if ($param['start_time']) {
                $where[] = ['r_created_at', '>=', strtotime($param['start_time'].' 00:00:00')];
            }
            if ($param['end_time']) {
                $where[] = ['r_created_at', '<=', strtotime($param['end_time'].' 23:59:59')];
            }
        }
        //最后跟进时间
        if ($request->input('date_type') == 2){
            if ($param['start_time']) {
                $where[] = ['r_follow_time', '>=', strtotime($param['start_time'].' 00:00:00')];
            }
            if ($param['end_time']) {
                $where[] = ['r_follow_time', '<=', strtotime($param['end_time'].' 23:59:59')];
            }
        }
        //交房时间
        if ($request->input('date_type') == 3){
            if ($param['start_time']) {
                $where[] = ['making_room', '>=', strtotime($param['start_time'].' 00:00:00')];
            }
            if ($param['end_time']) {
                $where[] = ['making_room', '<=', strtotime($param['end_time'].' 23:59:59')];
            }
        }

        //建房年代
        if ($request->input('date_type') == 4){
            if ($param['start_time']) {
                $where[] = ['building_s', '>=', strtotime($param['start_time'].' 00:00:00')];
            }
            if ($param['end_time']) {
                $where[] = ['building_s', '<=', strtotime($param['end_time'].' 23:59:59')];
            }
        }
        //委托时间
        if($request->input('date_type') == 5){
            if($request->input('start_time')){
                $where[] = ['r_entrust_at', '>=', $param['start_time'].' 00:00:00'];
            }
            if($request->input('end_time')){
                $where[] = ['r_entrust_at', '<=', $param['end_time'].' 23:59:59'];
            }
        }
        //钥匙房  checking_way  149 有钥匙
        if($request->input('checking_way') && $request->input('checking_way') != 'false'){
            $where[] = ['checking_way' , 149];
        }
        //房屋类型
        if($request->input('housing_types')){
            $where[] = ['housing_types' , $param['housing_types']];
        }

        //房型
        if($request->input('roomtype')){
            $where[] = ['ri_room_type' , $param['roomtype']];
        }

        //层数
        if($request->input('numlayers')){
            $where[] = ['ri_numbe_layers' , $param['numlayers']];
        }

        //朝向
        if($request->input('oriented')){
            $where[] = ['ri_oriented' , $param['oriented']];
        }
        //关键词智能搜索
        $keywords = '';
        if ($request->input('keywords')){
            $keywords = trim($request->input('keywords'));
        }
        $list = $roomInfo->listRoom(env('PAGE_LIMIT_ADMIN'), $where, $keywords, 0);
        if (!$list) {
            return $this->error(Error::NULL_DATA);
        }

        foreach($list as $k=>$v){
            $v->r_entrust_at = $v->r_entrust_at != null ? date('Y-m-d',$v->r_entrust_at) : '';//委托时间
            $v->making_room = $v->making_room != null ? date('Y-m-d',$v->making_room) : '';//交房时间
            $v->building_s = $v->building_s != null ? date('Y',$v->building_s) : '';//建房年代
            $v->r_follow_time = $v->r_follow_time != null ? date('Y-m-d',$v->r_follow_time) : '';
            $v->building_name = $roomWordbook->getWordbook($v->building_id); //楼盘字典
            $v->use_name    = SystemType::getTypeDetail($v->use_type);         //用途
            $v->housing_name = SystemType::getTypeDetail($v->housing_types);  //房屋类型
            $v->type_of_house_name = SystemType::getTypeDetail($v->type_of_house_sale);  //房屋出售类型
            $v->disc_name = SystemType::getTypeDetail($v->disc_type);    //盘类型  私盘  公盘
            $v->trading_name = SystemType::getTypeDetail($v->trading_type); //交易类型
            $v->trading_state_name = SystemType::getTypeDetail($v->status); //交易状态类型
            $v->rents_name = SystemType::getTypeDetail($v->rents_type);            //租价类型
            $v->taxes_fees_name = SystemType::getTypeDetail($v->taxes_fees);            //包税费类型
            $v->entrust_name = SystemType::getTypeDetail($v->entrust_way);    //委托方式
            $v->source_name = SystemType::getTypeDetail($v->source_type);    //来源id
            $v->status_quo_name = SystemType::getTypeDetail($v->status_quo);    //现状
            $v->decoration_name = SystemType::getTypeDetail($v->decoration);    //装修
            $v->furniture_name = SystemType::getTypeDetail($v->furniture);    //家具
            $v->appliance_name = SystemType::getTypeDetail($v->appliance);    //家电
            $v->rights_name = SystemType::getTypeDetail($v->rights_type);    //产权类型
            $v->certificate_name = SystemType::getTypeDetail($v->certificate_type);    //证件类型
            $v->payment_name = SystemType::getTypeDetail($v->payment_type);    //付款类型
            $v->pay_on_name = SystemType::getTypeDetail($v->pay_on_type);    //付拥类型
            $v->fence_type_name = SystemType::getTypeDetail($v->fence_type);    //围墙类型
            $v->wc_name = SystemType::getTypeDetail($v->wc_type);    //厕所类型
            $v->dorm_name = SystemType::getTypeDetail($v->dorm_type);    //宿舍类型
            $v->lot_name = SystemType::getTypeDetail($v->lot_type);    //地段类型
            $v->air_name = SystemType::getTypeDetail($v->air_type);    //空调类型
            $v->canteen_name = SystemType::getTypeDetail($v->canteen_type);    //食堂类型
            $v->checking_way_name = SystemType::getTypeDetail($v->checking_way);    //看房方式

            //多选框数据========配套
            $support_name = [];
            if($v->support){
                $support_arr = explode(',',$v->support);
                foreach($support_arr as $key => $val){
                    $support = SystemType::getTypeDetail($val);    //'配套
                    array_push($support_name, $support);
                }
            }
            $v->support_name = implode(',', $support_name);
            //多选框数据========行业
            $industry_name = [];
            if($v->industry_type){
                $industry_arr = explode(',',$v->industry_type);
                foreach($industry_arr as $key => $val){
                    $industry = SystemType::getTypeDetail($val);
                    array_push($industry_name, $industry);
                }
            }
            $v->industry_name = implode(',', $industry_name);
            //根据用途变换的输入款  将数据库json字符串转换成数组
            $v->r_info = json_decode($v->r_info, true);
            //房源明细列表
            $v->r_detaile_list = json_decode($v->r_detaile_list, true);

            $v->roomInfo = $roomInfo->getImptantInfo($v->id);//快速预览信息与跟进
            $v->roomFollow = $roomInfo->fastRoomFollow($v->id);//获取跟进最大5条
        }
        return $this->success('ok', $list);
     }


    /**
     * 根据房源id获取房源详情
     */
    public function detail(Request $request)
    {
        if (!$request->input('id')) {
            return $this->error(Error::PARAM_MISSING);
        }
        $room = new RoomInfo();
        $detail = $room->detail($request->input('id'));
        if(!$detail){
            return $this->error(Error::INVALID_ARUGMENT);
        }
        $roomWordbook = new RoomWordbook();
        //判断当前登陆员工的权限
//        $duserInfo = Auth::user();
//        $authories = explode(',', $duserInfo['authories']);//权限=============后期加权限判断
//        $uId = $duserInfo['u_id'];//用户ID

        $detail->building_s = date('Y', $detail->building_s);
        //盘类型(35 公盘     36私盘   37封盘    38下定盘  39斡旋盘)
        //权限判断的时候  根据盘的类型   在根据有没有查看盘的权限  做处理
//        if ($detail->source_uid != $uId && ($detail->disc_type == 36 || $detail->disc_type == 37 || $detail->disc_type == 38 || $detail->disc_type == 39)){
//            $detail->owner_phone='';
//            $detail->contact_phone='';
//        }
        //区县名称
        $detail->a_id_name    = AreaController::getAreaName($detail->a_id);
        $detail->building_name = $roomWordbook->getWordbook($detail->building_id); //楼盘字典
        $detail->use_name    = SystemType::getTypeDetail($detail->use_type);         //用途
        $detail->housing_name = SystemType::getTypeDetail($detail->housing_types);  //房屋类型
        $detail->type_of_house_name = SystemType::getTypeDetail($detail->type_of_house_sale);  //房屋出售类型
        $detail->disc_name = SystemType::getTypeDetail($detail->disc_type);    //盘类型  私盘  公盘
        $detail->trading_name = SystemType::getTypeDetail($detail->trading_type); //交易类型
        $detail->trading_state_name = SystemType::getTypeDetail($detail->status); //交易状态类型
        $detail->rents_name = SystemType::getTypeDetail($detail->rents_type);            //租价类型
        $detail->taxes_fees_name = SystemType::getTypeDetail($detail->taxes_fees);            //包税费类型
        $detail->entrust_name = SystemType::getTypeDetail($detail->entrust_way);    //委托方式
        $detail->source_name = SystemType::getTypeDetail($detail->source_type);    //来源id
        $detail->status_quo_name = SystemType::getTypeDetail($detail->status_quo);    //现状
        $detail->decoration_name = SystemType::getTypeDetail($detail->decoration);    //装修
        $detail->furniture_name = SystemType::getTypeDetail($detail->furniture);    //家具
        $detail->appliance_name = SystemType::getTypeDetail($detail->appliance);    //家电
        $detail->rights_name = SystemType::getTypeDetail($detail->rights_type);    //产权类型
        $detail->certificate_name = SystemType::getTypeDetail($detail->certificate_type);    //证件类型
        $detail->payment_name = SystemType::getTypeDetail($detail->payment_type);    //付款类型
        $detail->pay_on_name = SystemType::getTypeDetail($detail->pay_on_type);    //付拥类型
        $detail->fence_type_name = SystemType::getTypeDetail($detail->fence_type);    //围墙类型
        $detail->wc_name = SystemType::getTypeDetail($detail->wc_type);    //厕所类型
        $detail->dorm_name = SystemType::getTypeDetail($detail->dorm_type);    //宿舍类型
        $detail->lot_name = SystemType::getTypeDetail($detail->lot_type);    //地段类型
        $detail->air_name = SystemType::getTypeDetail($detail->air_type);    //空调类型
        $detail->canteen_name = SystemType::getTypeDetail($detail->canteen_type);    //食堂类型
        $detail->checking_way_name = SystemType::getTypeDetail($detail->checking_way);    //看房方式
        //多选框数据========配套
        $support_name = [];
        if($detail->support){
            $support_arr = explode(',',$detail->support);
            foreach($support_arr as $key => $val){
                $support = SystemType::getTypeDetail($val);    //'配套
                array_push($support_name, $support);
            }
        }
        $detail->support_name = implode(',', $support_name);
        //多选框数据========行业
        $industry_name = [];
        if($detail->industry_type){
            $industry_arr = explode(',',$detail->industry_type);
            foreach($industry_arr as $key => $val){
                $industry = SystemType::getTypeDetail($val);
                array_push($industry_name, $industry);
            }
        }
        $detail->industry_name = implode(',', $industry_name);
        //根据用途变换的输入款  将数据库json字符串转换成数组
        $detail->r_info = json_decode($detail->r_info, true);
        //房源明细列表
        $detail->r_detaile_list = json_decode($detail->r_detaile_list, true);
//        $detail->roomInfo = $roomInfo->getImptantInfo($detail->id);//快速预览信息与跟进
//        $detail->roomFollow = $roomInfo->fastRoomFollow($detail->id);//获取跟进最大5条

        return $this->success('ok', $detail);
    }

    /**交易合同 诚意金  等简单查找房源列表接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function houseListFast(Request $request)
    {
        //房源状态等于1 未删除房源
        $where[] = ['room_status',1];
        $param = $request->all();
        //部门
        if ($request->input('r_d_id')){
            $where[] = ['r_d_id', $param['r_d_id']];
        } else {
            $where[] = ['r_d_id', Auth::user()['u_d_id']];
        }
        //录入人ID
        if ($request->input('source_uid')){
            $where[] = ['source_uid', $param['source_uid']];
        } else {
            $where[] = ['source_uid', Auth::user()['u_id']];
        }
        //关键词智能搜索
        $keywords = '';
        if ($request->input('keywords')){
            $keywords = trim($request->input('keywords'));
        }
        //区县ID
        if ($request->input('a_id')){
            $where[] = ['a_id', $param['a_id']];
        }
        //交易
        if($request->input('trading_type')){
            $where[] = ['status' , $param['status']];
        }
        //状态
        if($request->input('status')){
            $where[] = ['status' , $param['status']];
        }
        $roomInfo = new RoomInfo();
        $list = $roomInfo->listRoomFast(env('PAGE_LIMIT_ADMIN'), $where, $keywords);
        if (!$list) {
            return $this->error(Error::NULL_DATA);
        }
        $roomWordbook = new RoomWordbook();
//        $roomwordbookinfo = new RoomWordbookInfo();
        foreach($list as $k=>$v){
            $v->trading_type = SystemType::getTypeDetail($v->trading_type);//交易类型
            $v->a_id = AreaController::getAreaName($v->a_id);//城区
            $v->building_id = $roomWordbook->getWordbook($v->building_id); //楼盘字典
//            $v->few_building  = $roomwordbookinfo->getWordbookInfoName($v->few_building);//栋座
            $v->status = SystemType::getTypeDetail($v->status); //交易状态类型
        }
        return $this->success('ok', $list);

    }

    /**
     * 添加房源之前根据房源的区ID、楼盘字典  栋座  位置  查询该房源是不是重复录入
     */
    public function checkHouse(Request $request,RoomInfo $RoomInfo)
    {
        $params = $request->except('token');
        $validator =  RoomInfoVail::check($params);
        if (!$validator) {
            //参数不完整
            return $this->error(Error::PARAM_MISSING);
        }
        $rId = 0;
        if ($request->input('r_id')) { //添加的时候没有房源的ID   修改的时候有房源ID
            $rId = $request->input('r_id');
        }
        //获取根据楼盘字典的名称楼盘字典的ID  getRoomId
        $RoomWordBook = new RoomWordbook();
        $params['building_id'] = $RoomWordBook->getRoomId($params['building_id']);
        if (!$params['building_id']) {
            return $this->error(Error::NO_PROPERTY);//楼盘字典不存在
        }
        $data = $RoomInfo->verificationRoomRepeat($params, $rId);
        if (!$data) {
            return $this->error(Error::CHECK_HOUSE);
        }
        $data->province_code = $this->province_code;//省code
        $data->city_code = $this->city_code;//市CODE
        $data->city = $this->city;//市名字
//        $area_list = DB::table('area')->where(['parentId' => $this->city_code])->get();
        $data->r_entrust_at = date('Y-m-d', $data->r_entrust_at);//委托时间
        $data->making_room = date('Y-m-d', $data->making_room);//交房时间
        $data->building_s = date('Y', $data->building_s);
        $roomWordbook = new RoomWordbook();
        $data->building_name = $roomWordbook->getWordbook($data->building_id); //楼盘字典
        $data->use_name    = SystemType::getTypeDetail($data->use_type);         //用途
        $data->housing_name = SystemType::getTypeDetail($data->housing_types);  //房屋类型
        $data->type_of_house_name = SystemType::getTypeDetail($data->type_of_house_sale);  //房屋出售类型
        $data->disc_name = SystemType::getTypeDetail($data->disc_type);    //盘类型  私盘  公盘
        $data->trading_name = SystemType::getTypeDetail($data->trading_type); //交易类型
        $data->trading_state_name = SystemType::getTypeDetail($data->status); //交易状态类型
        $data->rents_name = SystemType::getTypeDetail($data->rents_type);            //租价类型
        $data->taxes_fees_name = SystemType::getTypeDetail($data->taxes_fees);            //包税费类型
        $data->entrust_name = SystemType::getTypeDetail($data->entrust_way);    //委托方式
        $data->source_name = SystemType::getTypeDetail($data->source_type);    //来源id
        $data->status_quo_name = SystemType::getTypeDetail($data->status_quo);    //现状
        $data->decoration_name = SystemType::getTypeDetail($data->decoration);    //装修
        $data->furniture_name = SystemType::getTypeDetail($data->furniture);    //家具
        $data->appliance_name = SystemType::getTypeDetail($data->appliance);    //家电
        $data->rights_name = SystemType::getTypeDetail($data->rights_type);    //产权类型
        $data->certificate_name = SystemType::getTypeDetail($data->certificate_type);    //证件类型
        $data->payment_name = SystemType::getTypeDetail($data->payment_type);    //付款类型
        $data->pay_on_name = SystemType::getTypeDetail($data->pay_on_type);    //付拥类型
        $data->fence_type_name = SystemType::getTypeDetail($data->fence_type);    //围墙类型
        $data->wc_name = SystemType::getTypeDetail($data->wc_type);    //厕所类型
        $data->dorm_name = SystemType::getTypeDetail($data->dorm_type);    //宿舍类型
        $data->lot_name = SystemType::getTypeDetail($data->lot_type);    //地段类型
        $data->air_name = SystemType::getTypeDetail($data->air_type);    //空调类型
        $data->canteen_name = SystemType::getTypeDetail($data->canteen_type);    //食堂类型
        $data->checking_way_name = SystemType::getTypeDetail($data->checking_way);    //看房方式
        //多选框数据循环查找======配套
        $support_name = [];
        if($data->support){
            $support_arr = explode(',',$data->support);
            foreach($support_arr as $key => $val){
                $support = SystemType::getTypeDetail($val);    //'配套
                array_push($support_name, $support);
            }
        }
        $data->support_name = implode(',', $support_name);
        //多选框数据========行业
        $industry_name = [];
        if($data->industry_type){
            $industry_arr = explode(',',$data->industry_type);
            foreach($industry_arr as $key => $val){
                $industry = SystemType::getTypeDetail($val);    //'配套
                array_push($industry_name, $industry);
            }
        }
        $data->industry_name = implode(',', $industry_name);

        //根据用途变换的输入款  将数据库json字符串转换成数组
        $data->r_info = json_decode($data->r_info, true);
        //房源明细列表
        $data->r_detaile_list = json_decode($data->r_detaile_list, true);
        return $this->success('ok', $data);
    }



    /**
     * 添加房源数据信息
     */
    public function insertHouse (Request $request,RoomInfo $RoomInfo, Customers $customers)
    {
        $params = $request->except('token');
        $validator =  RoomInfoVail::validate($params);
        if (!$validator) {
            //参数不完整
            return $this->error(Error::PARAM_MISSING);
        }
        //获取根据楼盘字典的名称楼盘字典的ID  getRoomId
        $RoomWordBook = new RoomWordbook();
        $params['building_id'] = $RoomWordBook->getRoomId($params['building_id']);
        if (!$params['building_id']) {
            return $this->error(Error::NO_PROPERTY);//楼盘字典不存在
        }
        $data = $RoomInfo->verificationRoomRepeat($params, 0);
        if ($data) {
            return $this->error(Error::REPEATED_ROOM);
        }
        //根据房源用途不同前台传的不同类型字段值,转换成json字符串，输出时直接转换成json数组前台取值
        $json_info = $request->input('r_info','{}');
        $params['r_info'] = json_encode($json_info);
        //房源明细列表 将前台提交的明细数组转换成json 以name值为键 对应输入框值
        $json_detaile = $request->input('r_detaile_list','{}');
        $params['r_detaile_list'] = json_encode($json_detaile);

        //建房年代
        if ($request->input('building_s')) {
            $params['building_s'] = strtotime($params['building_s'].'-01-01 00:00:00');
        }
        //委托时间
        if ($request->input('r_entrust_at')) {
            $params['r_entrust_at'] = strtotime($params['r_entrust_at']);
        } else {
            $params['r_entrust_at'] = time();
        }
        //交房时间
        if ($params['making_room']) {
            $params['making_room'] = strtotime($params['making_room']);
        }
        $params['r_created_at'] = time();//创建时间
        $params['r_follow_time'] = time();//跟进时间
        $params['r_updated_at'] = time(); //修改时间
        $rid = $RoomInfo->addRoomInfo($params);

        if (!$rid) {
            //添加失败
            return $this->error(Error::ADD_ERROR);
        }

        //按照用途过滤  14 为“其他类型” 匹配所有用途的客源
        if ($params['use_type'] != 14) {
            $map[] = ['c_use_type',  $params['use_type']];
        }

        //按租售类型查找
        //   房源  出售 93    出租 94    租售 95
        //   客源  求购 451  求租 452    租购 453

        if ($params['trading_type'] == 93) {
            //房源交易类型是出售
            $map[] = ['c_trading_type', '<>', 452];

        } elseif ($params['trading_type'] == 94) {
            //房源交易类型是出租
            $map[] = ['c_trading_type', '<>', 451];
        }

        //按价格查找
        if($params['trading_type'] == 93){  //录入为出售 查询条件按租价查找客源
            $map[] = ['c_price_min', '<=', $params['price']];
            $map[] = ['c_price_max', '>=', $params['price']];
        }elseif($params['trading_type'] == 94){   //录入房源为租时查找需要租的价格匹配客源
            $map[] = ['c_rent_price_min', '<=', $params['rents']];
            $map[] = ['c_rent_price_max', '>=', $params['rents']];
        }else{
            $map[] = ['c_price_min', '<=', $params['price']];
            $map[] = ['c_price_max', '>=', $params['price']];
            $map[] = ['c_rent_price_min', '<=', $params['rents']];
            $map[] = ['c_rent_price_max', '>=', $params['rents']];
        }
        //按面积查找
        if($request->has('r_acreage') && $params['r_acreage'] !=''){
            $map[] = ['c_acreage_min', '<=', $params['r_acreage']];
            $map[] = ['c_acreage_max', '>=', $params['r_acreage']];
        }
        //智能匹配返回相对应客源列表
        $data['customers_list'] = $customers->getCustomersList($map, env('PAGE_LIMIT_ADMIN'));
        $data['rid'] = $rid;
        $data['important_information'] = $RoomInfo->getImptantInfo($rid);
        return $this->success('ok', $data);
    }

   /*
    * 修改房源
    * Wu Ning
    * 2018 05 27
    */
//    public function updataHouse(Request $request,RoomInfo $RoomInfo, Customers $customers)
//    {
//        $params = $request->except('token');
//        $validator =  RoomInfoVail::validate($params);
//        if (!$validator) {
//            //参数不完整
//            return $this->error(Error::PARAM_MISSING);
//        }
//        $res = $RoomInfo->updataHouse($params);
//        if (!$res) {
//            //修改失败
//            return $this->error(Error::EDIT_ERROR);
//        }
//
//        //按租售类型查找
//        //   房源  出售 93    出租 94    租售 95
//        //   客源  求购 451  求租 452    租购 453
//        if ($params['trading_type'] == 93) {
//            //房源交易类型是出售
//            $map[] = ['c_trading_type', '<>', 452];
//
//        } elseif ($params['trading_type'] == 94) {
//            //房源交易类型是出租
//            $map[] = ['c_trading_type', '<>', 451];
//        }
//        //按价格查找
//        if(intval($params['trading_type']) == 93){  //录入为售房 查询条件按租价查找客源
//            $map[] = ['c_price_min', '<=', $params['price']];
//            $map[] = ['c_price_max', '>=', $params['price']];
//        }elseif(intval($params['trading_type']) == 94){   //录入房源为租时查找需要租的价格匹配客源
//            $map[] = ['c_rent_price_min', '<=', $params['rents']];
//            $map[] = ['c_rent_price_max', '>=', $params['rents']];
//        }else{
//            $map[] = ['c_price_min', '<=', $params['price']];
//            $map[] = ['c_price_max', '>=', $params['price']];
//            $map[] = ['c_rent_price_min', '<=', $params['rents']];
//            $map[] = ['c_rent_price_max', '>=', $params['rents']];
//        }
//        //按面积查找
//        if($request->has('r_acreage') && $params['r_acreage'] !=''){
//            $map[] = ['c_acreage_min', '<=', $params['r_acreage']];
//            $map[] = ['c_acreage_max', '>=', $params['r_acreage']];
//        }
//        //智能匹配返回相对应客源列表
//        $customers_list = $customers->getCustomersList($map, env('PAGE_LIMIT_ADMIN'));
//        return $this->success('ok', $customers_list);
//    }
    /*
     * 房源回收站列表
     */
    public function roomRecyclebinLists(Request $request,RoomInfo $RoomInfo){
        $param = $request->all();
        $where = [];
        if($request->input('start_time')){
            $where[] = ['r_updated_at', '>=', strtotime($param['start_time'].' 00:00:00')];
        } else {
            $where[] = ['r_updated_at', '>=', strtotime(date('Y-m-d',strtotime('-3 month')).' 00:00:00')];
        }

        if($request->input('end_time')){
            $where[] = ['r_updated_at', '<=', strtotime($param['end_time'].' 23:59:59')];
        } else {
            $where[] = ['r_updated_at', '<=', time()];
        }

        //关键词智能搜索
        $keywords = '';
        if ($request->input('keywords')){
            //客源编号 客户姓名 客户电话
            $keywords = trim($request->input('keywords'));
        }

        $list = $RoomInfo->recycleBinList(env('PAGE_LIMIT_ADMIN'),$where,$keywords);
        if (!$list) {
            $data['start'] = date('Y-m-d',strtotime('-3 month'));
            $data['end']  = date('Y-m-d',time());
            return $this->error(Error::NULL_DATA,$data);
        }
         $start = date('Y-m-d',strtotime('-3 month'));
        $end = date('Y-m-d',time());
        return $this->success('ok', $list,$start,$end);
    }

    /*
     * 房源软删除 与 恢复
     */
    public function softDelHouse(Request $request,RoomInfo $RoomInfo)
    {
        $params = $request->except('token');
        $validator =  RoomInfoVail::updateStatus($params);
        if (!$validator) {
            //参数不完整
            return $this->error(Error::PARAM_MISSING);
        }
        $res = $RoomInfo->softDelHouse($params['id']);
        if($res === -1){
            return $this->error(Error::OPERATION_ERROR);
        }

        if (!$res) {
            return $this->error(Error::OPERATION_ERROR);
        }
        return $this->success('ok', '操作成功！');
    }

    /*
     *  永久删除房源
     */
    public function DelHouse(Request $request,RoomInfo $RoomInfo)
    {
        $params = $request->except('token');
        $validator =  RoomInfoVail::updateStatus($params);
        if (!$validator) {
            return $this->error(Error::PARAM_MISSING);
        }
        $res = $RoomInfo->DelHouse($params['id']);
        if (!$res) {
            return $this->error(Error::DEL_ERROR);
        }
        return $this->success('ok', '删除成功！');
    }

    /**修改房源信息   业绩分配
     * @param Request $request    addAchievement
     * @param RoomInfo $roomInfo
     * @return \Illuminate\Http\JsonResponse
     */
    public function updataHouse(Request $request,RoomInfo $roomInfo, Customers $customers)
    {
//        $param = $request->except('token');
        $param = $request->except('token', 'province_code', 'city_code', 'city', 'a_id_name', 'building_name', 'use_name', 'housing_name', 'type_of_house_name',
            'disc_name', 'trading_name', 'trading_state_name', 'rents_name', 'taxes_fees_name', 'entrust_name', 'source_name',
            'status_quo_name', 'decoration_name', 'furniture_name', 'appliance_name', 'rights_name', 'certificate_name',
            'payment_name', 'pay_on_name', 'fence_type_name', 'wc_name', 'dorm_name', 'lot_name', 'air_name', 'canteen_name', 'checking_way_name',
            'support_name', 'industry_name','u_username', 'name', 'roomInfo', 'roomFollow','r_follow_time');
        if(!RoomInfoVail::validate($param)){
            return $this->error(Error::PARAM_MISSING);
        }
        if (!$request->input('id')) {
            return $this->error(Error::PARAM_MISSING);
        }
        //委托时间
        if ($request->input('r_entrust_at')) {
            $param['r_entrust_at'] = strtotime($param['r_entrust_at']);
        }

        //获取根据楼盘字典的名称楼盘字典的ID  getRoomId
        $RoomWordBook = new RoomWordbook();
        $param['building_id'] = $RoomWordBook->getRoomId($param['building_id']);
        if (!$param['building_id']) {
            return $this->error(Error::NO_PROPERTY);//楼盘字典不存在
        }
        $data = $roomInfo->verificationRoomRepeat($param, $request->input('id'));
        if ($data) {
            return $this->error(Error::REPEATED_ROOM);
        }

        //根据房源用途不同前台传的不同类型字段值,转换成json字符串，输出时直接转换成json数组前台取值
        $json_info = $request->input('r_info','{}');
        $param['r_info'] = json_encode($json_info);
        //房源明细列表 将前台提交的明细数组转换成json 以name值为键 对应输入框值
        $json_detaile = $request->input('r_detaile_list','{}');
        $param['r_detaile_list'] = json_encode($json_detaile);
        //建房年代
        if ($request->input('building_s')) {
            $param['building_s'] = strtotime($param['building_s']);
        }
        //交房时间
        if ($request->input('making_room')) {
            $param['making_room'] = strtotime($param['making_room']);
        }
        $param['r_updated_at'] = time(); //修改时间
        $param['r_follow_time'] = time();//最后跟进时间
        $res = $roomInfo->saveRoomStatus($param);
        if ($res === -1) {
            //这里就要进行业绩分配了
            return $this->error(Error::NEED_PER_DISTRIBUTION);
        }
        if (!$res) {
            return $this->error(Error::EDIT_ERROR);
        }
        $map = [];

        //按照用途过滤  14 为“其他类型” 匹配所有用途的客源
        if ($param['use_type'] != 14) {
            $map[] = ['c_use_type',  $param['use_type']];
        }
        //按租售类型查找
        //   房源  出售 93    出租 94    租售 95
        //   客源  求购 451  求租 452    租购 453
        if ($param['trading_type'] == 93) {
            //房源交易类型是出售
            $map[] = ['c_trading_type', '<>', 452];

        } elseif ($param['trading_type'] == 94) {
            //房源交易类型是出租
            $map[] = ['c_trading_type', '<>', 451];
        }
        //按价格查找
        if(intval($param['trading_type']) == 93){  //录入为售房 查询条件按租价查找客源
            if ($request->has('price') && $param['price'] !='') {
                $map[] = ['c_price_min', '<=', $param['price']];
                $map[] = ['c_price_max', '>=', $param['price']];
            }
        }elseif(intval($param['trading_type']) == 94){   //录入房源为租时查找需要租的价格匹配客源
            if ($request->has('rents') && $param['rents'] !='') {
                $map[] = ['c_rent_price_min', '<=', $param['rents']];
                $map[] = ['c_rent_price_max', '>=', $param['rents']];
            }
        }else{
            if ($request->has('price') && $param['price'] !='' && $request->has('rents') && $param['rents'] !='') {
                $map[] = ['c_price_min', '<=', $param['price']];
                $map[] = ['c_price_max', '>=', $param['price']];
                $map[] = ['c_rent_price_min', '<=', $param['rents']];
                $map[] = ['c_rent_price_max', '>=', $param['rents']];
            }
        }
        //按面积查找
        if($request->has('r_acreage') && $param['r_acreage'] !=''){
            $map[] = ['c_acreage_min', '<=', $param['r_acreage']];
            $map[] = ['c_acreage_max', '>=', $param['r_acreage']];
        }
        //智能匹配返回相对应客源列表
        $data['customers_list'] = $customers->getCustomersList($map, env('PAGE_LIMIT_ADMIN'));
        $data['rid'] = $request->input('id');
        $data['important_information'] = $roomInfo->getImptantInfo($request->input('id'));
        return $this->success('ok', $data);

    }


    /**
     * 点击编辑房源按钮   根据房源的ID   匹配客源信息
     */
    public function matchCustomerInfo(Request $request,RoomInfo $roomInfo, Customers $customers)
    {
        if (!$request->input('id')) {
            return $this->error(Error::PARAM_MISSING);
        }
        //根据房源的ID   查询要匹配的信息
        $info = $roomInfo->getRoomMatch($request->input('id'));
        if (!$info) {
            return $this->error(Error::ROOM_DOES_NOT_EXIST);
        }
        $map = [];
        //按照用途过滤  14 为“其他类型” 匹配所有用途的客源
        if ($info->use_type != 14) {
            $map[] = ['c_use_type',  $info->use_type];
        }

        //按租售类型查找
        //   房源  出售 93    出租 94    租售 95
        //   客源  求购 451  求租 452    租购 453
        if ($info->trading_type == 93) {
            //房源交易类型是出售
            $map[] = ['c_trading_type', '<>', 452];

        } elseif ($info->trading_type == 94) {
            //房源交易类型是出租
            $map[] = ['c_trading_type', '<>', 451];
        }
        //按价格查找
        if($info->trading_type == 93){  //录入为售房 查询条件按租价查找客源
            $map[] = ['c_price_min', '<=', $info->price];//120  150
            $map[] = ['c_price_max', '>=', $info->price];//150  150
        }elseif($info->trading_type == 94){   //录入房源为租时查找需要租的价格匹配客源
            $map[] = ['c_rent_price_min', '<=', $info->rents];
            $map[] = ['c_rent_price_max', '>=', $info->rents];
        }else{
            $map[] = ['c_price_min', '<=', $info->price];
            $map[] = ['c_price_max', '>=', $info->price];
            $map[] = ['c_rent_price_min', '<=', $info->rents];
            $map[] = ['c_rent_price_max', '>=', $info->rents];
        }
        //按面积查找
            $map[] = ['c_acreage_min', '<=', $info->r_acreage];
            $map[] = ['c_acreage_max', '>=', $info->r_acreage];
            //dd($map);
        //智能匹配返回相对应客源列表
        $data['customers_list'] = $customers->getCustomersList($map, env('PAGE_LIMIT_ADMIN'));
        $data['rid'] = $request->input('id');
        $data['important_information'] = $roomInfo->getImptantInfo($request->input('id'));
        return $this->success('ok', $data);
    }


    /**
     * 业绩分配
     */
    public function addAchievement(Request $request,RoomInfo $roomInfo, Customers $customers)
    {
        //这里开始正式的业绩划分
        $param = $request->except('token');
        if(!AchievementVali::validate($param)){
            return $this->error(Error::PARAM_MISSING);
        }
        if (!$request->input('id')) {
            return $this->error(Error::PARAM_MISSING);
        }
//        $r_Info = $request->except('token', 'c_id', 'a_type', 'a_money', 'a_rate', 'a_uid', 'a_remark');//所有关于房源的信息
        $r_Info = $request->except('token', 'a_id_name', 'building_name', 'use_name', 'housing_name', 'type_of_house_name',
            'disc_name', 'trading_name', 'trading_state_name', 'rents_name', 'taxes_fees_name', 'entrust_name', 'source_name',
            'status_quo_name', 'decoration_name', 'furniture_name', 'appliance_name', 'rights_name', 'certificate_name',
            'payment_name', 'pay_on_name', 'fence_type_name', 'wc_name', 'dorm_name', 'lot_name', 'air_name', 'canteen_name', 'checking_way_name',
            'support_name', 'industry_name','u_username', 'name', 'c_id', 'a_type', 'a_money', 'a_rate', 'a_uid', 'a_remark', 'roomInfo', 'roomFollow');


        $cId = $request->input('c_id');//选择的客源ID

        $type = $request->input('a_type');//单独完成 传1    多人完成 传2

        $money = $request->input('a_money');//总提成

        $rate = $request->input('a_rate');//提成比例字符串

        $a_uid = $request->input('a_uid');// 业绩分成员工ID

        $a_remark = $request->input('a_remark');// 业绩分成备注

        /**
         * 第一步  客源修改的所有信息拿到手   第二客源的ID 拿到手   第三划分业绩的人员和比例拿到手
         * 开始划分业绩
         */

        //根据房源用途不同前台传的不同类型字段值,转换成json字符串，输出时直接转换成json数组前台取值
        $json_info = $request->input('r_info','{}');
        $r_Info['r_info'] = json_encode($json_info);
        //房源明细列表 将前台提交的明细数组转换成json 以name值为键 对应输入框值
        $json_detaile = $request->input('r_detaile_list','{}');
        $r_Info['r_detaile_list'] = json_encode($json_detaile);
        //建房年代
        if ($request->input('building_s')) {
            $r_Info['building_s'] = strtotime($r_Info['building_s']);
        }
        //委托时间
        if ($request->input('r_entrust_at')) {
            $r_Info['r_entrust_at'] = strtotime($r_Info['r_entrust_at']);
        }
        //交房时间
        if ($request->input('making_room')) {
            $r_Info['making_room'] = strtotime($r_Info['making_room']);
        }
        //获取根据楼盘字典的名称楼盘字典的ID  getRoomId
        $RoomWordBook = new RoomWordbook();
        $r_Info['building_id'] = $RoomWordBook->getRoomId($r_Info['building_id']);
        if (!$r_Info['building_id']) {
            return $this->error(Error::NO_PROPERTY);//楼盘字典不存在
        }
        $r_Info['r_updated_at'] = time(); //修改时间
        $res = $roomInfo->performanceDistribution($r_Info, $cId, $type, $money, $rate, $a_uid, $a_remark);

        if ($res === -3) {
            //未知错误
            return $this->error(Error::PLEASE_CONTACT_ADMIN);
        }

        if ($res === -1) {
            //人员业绩分配不对等，请仔细检查人员的比例分配
            return $this->error(Error::PROPOR_DIS_MISTAKEN);
        }
        if ($res === -2) {
            //比例分配错误，所有比例总和只能为10
            return $this->error(Error::PROPOR_ONLY_TEN);
        }
        if (!$res) {
            //业绩分配失败
            return $this->error(Error::PROPOR_FAIL);
        }
//        return $this->success('ok', '业绩分配成功！');
        $map = [];
        //按租售类型查找
        //   房源  出售 93    出租 94    租售 95
        //   客源  求购 451  求租 452    租购 453
        if ($r_Info['trading_type'] == 93) {
            //房源交易类型是出售
            $map[] = ['c_trading_type', '<>', 452];

        } elseif ($r_Info['trading_type'] == 94) {
            //房源交易类型是出租
            $map[] = ['c_trading_type', '<>', 451];
        }
        //按价格查找
        if(intval($r_Info['trading_type']) == 93){  //录入为售房 查询条件按租价查找客源
            if ($request->has('price') && $r_Info['price'] !='') {
                $map[] = ['c_price_min', '<=', $r_Info['price']];
                $map[] = ['c_price_max', '>=', $r_Info['price']];
            }
        }elseif(intval($r_Info['trading_type']) == 94){   //录入房源为租时查找需要租的价格匹配客源
            if ($request->has('rents') && $r_Info['rents'] !='') {
                $map[] = ['c_rent_price_min', '<=', $r_Info['rents']];
                $map[] = ['c_rent_price_max', '>=', $r_Info['rents']];
            }
        }else{
            if ($request->has('price') && $r_Info['price'] !='' && $request->has('rents') && $r_Info['rents'] !='') {
                $map[] = ['c_price_min', '<=', $r_Info['price']];
                $map[] = ['c_price_max', '>=', $r_Info['price']];
                $map[] = ['c_rent_price_min', '<=', $r_Info['rents']];
                $map[] = ['c_rent_price_max', '>=', $r_Info['rents']];
            }
        }
        //按面积查找
        if($request->has('r_acreage') && $r_Info['r_acreage'] !=''){
            $map[] = ['c_acreage_min', '<=', $r_Info['r_acreage']];
            $map[] = ['c_acreage_max', '>=', $r_Info['r_acreage']];
        }
        //智能匹配返回相对应客源列表
        $data['customers_list'] = $customers->getCustomersList($map, env('PAGE_LIMIT_ADMIN'));
        $data['rid'] = $request->input('id');
        $data['important_information'] = $roomInfo->getImptantInfo($request->input('id'));
        return $this->success('ok', $data);
    }


    //添加房源的时候获取当前省市区   以及 默认各种类型
    public function getDefaultType(Request $request)
    {
//        $area_list = DB::table('area')->where(['parentId' => $this->city_code])->get();
        $branch_info = Auth::user();
        if (!$branch_info) {
            //公司ID ,系统管理组部门ID,   部门id ,员工Id,
            $branch_info = explode(',', Redis::get($request->input('apptoken')));
            $branch_id = $branch_info[0];
            $store_id =  $branch_info[2];
            $uid =  $branch_info[3];
        } else {
            $branch_id = $branch_info['u_b_id'];
            $store_id =  $branch_info['u_d_id'];
            $uid =  $branch_info['u_id'];
        }
        $data = [
            'province_code'     => $this->province_code,//省code
            'city_code'         => $this->city_code,//市code
            'city_name'         => $this->city,//市名字
            'store_id'          => $store_id,//部门ID
            'uid'               => $uid,//用户ID
            'day'               => date('Y-m-d',time()),//当天时间
            'area_name'         => DB::table('account_number_manager')->where('anm_id', $branch_id)->value('anm_area'),//区名字
//            'area_list'         => $area_list,//区县下拉框
        ];
        //《住宅、商住、其他》  房型40、厅57、卫65、阳台73、用途1、优选度27、
        //盘类型34、类型204、朝向81、交易92、状态96、
//        $arr = [40,57,65,73,1,27,34,204,81,92,96,106,704,111,118,128,136,147,576,219,603,679,233];
        $data['roomtype'] =  SystemType::storageRedis(40);//房型
        $data['hall'] =  SystemType::storageRedis(57);//厅
        $data['guard'] =  SystemType::storageRedis(65);//卫
        $data['balcony'] =  SystemType::storageRedis(73);//阳台
        $data['use'] =  SystemType::storageRedis(1);//用途
        $data['optimal'] =  SystemType::storageRedis(27);//优选度
        $data['plate'] =  SystemType::storageRedis(34);//盘类型

        $data['oriented'] =  SystemType::storageRedis(81);//朝向
        $data['transaction'] =  SystemType::storageRedis(92);//交易
        $data['status'] =  SystemType::storageRedis(96);//状态
        //包税费106、租价单位704、委托方式111、来源118、
        //付款128、 付佣136、看房 147
        //《商铺  铺厂 网点》   位置 576  层数 219
        //《写字楼 写厂》  级别603
        //《车位》 位置679     排量 233
        $data['package'] =  SystemType::storageRedis(106);//包税费
        $data['rentunit'] =  SystemType::storageRedis(704);//租价单位
        $data['delegation'] =  SystemType::storageRedis(111);//委托方式
        $data['source'] =  SystemType::storageRedis(118);//来源
        $data['payment'] =  SystemType::storageRedis(128);//付款
        $data['commission'] =  SystemType::storageRedis(136);//付佣
        $data['lookhouse'] =  SystemType::storageRedis(147);//看房
        $data['spw_position'] =  SystemType::storageRedis(576);//《商铺  铺厂 网点》位置
        $data['numlayers'] =  SystemType::storageRedis(219);//层数
        $data['level'] =  SystemType::storageRedis(603);//级别《写字楼  写厂》
        $data['c_position'] =  SystemType::storageRedis(679);//车位--位置
        $data['displacement'] =  SystemType::storageRedis(233);//排量

        /**
         * 类型
         */
        //《住宅、商住、其他》--- 类型 204
        $data['zsq_type'] =  SystemType::storageRedis(204);

        //《商铺  铺厂 网点》----类型 237
        $data['spw_type'] =  SystemType::storageRedis(237);

        //《写字楼  写厂》-----类型  277
        $data['xx_type'] =  SystemType::storageRedis(277);

        //厂房 仓库-----类型  362
        $data['cc_type'] =  SystemType::storageRedis(362);

        //地皮-----类型  369
        $data['dp_type'] =  SystemType::storageRedis(369);

        //车位---------类型  394
        $data['c_type'] =  SystemType::storageRedis(394);
        /**
         * 现状
         */
        //住宅、商住、其他 -----现状  152
        $data['zsq_statusquo'] =  SystemType::storageRedis(152);

        //商铺、 铺厂、 网点 -----现状  243
        $data['spw_statusquo'] =  SystemType::storageRedis(243);

        //写厂  写字楼  -----现状  284
        $data['xx_statusquo'] =  SystemType::storageRedis(284);

        //厂房、仓库、地皮 --现状  314
        $data['ccd_statusquo'] =  SystemType::storageRedis(314);

        //车位------现状
        $data['c_statusquo'] =  SystemType::storageRedis(375);
        /**
         *产权
         */
        //产权  156 -----住宅、商住、其他
        $data['zsq_property'] = SystemType::storageRedis(156);

        //产权 247  ----------商铺、铺厂、网点
        $data['spw_property'] = SystemType::storageRedis(247);

        //产权 288  ------------写字楼  写厂
        $data['xx_property'] = SystemType::storageRedis(288);

        //产权 354  --------------厂房 仓库  地皮
        $data['ccd_property'] = SystemType::storageRedis(354);

        //产权 379   -----------------车位
        $data['c_property'] = SystemType::storageRedis(379);
        /**
         * 装修
         */
        //装修---------住宅、商住、其他  162
        $data['zsq_decoration'] = SystemType::storageRedis(162);

        //装修  ----------商铺、铺厂、网点 251
        $data['spw_decoration'] = SystemType::storageRedis(251);

        //装修  ------------写字楼  写厂 292
        $data['xx_decoration'] = SystemType::storageRedis(292);
        /**
         *围墙
         */
        //围墙    --------------厂房 仓库  地皮 318
        $data['ccd_fencethree'] = SystemType::storageRedis(318);

        //围墙    --------------车位  318
        $data['c_fencethree'] = SystemType::storageRedis(318);
        /**
         * 证件
         */
        //证件 -----------------住宅、商住、其他 172
        $data['zsq_document'] = SystemType::storageRedis(172);

        //证件 -----------------商铺、铺厂、网点 258
        $data['spw_document'] = SystemType::storageRedis(258);

        //证件 -----------------写字楼、写厂 299
        $data['xx_document'] = SystemType::storageRedis(299);

        //证件 -----------------厂房、仓库、地皮 358
        $data['ccd_document'] = SystemType::storageRedis(358);

        //证件 -----------------车位 385
        $data['c_document'] = SystemType::storageRedis(385);
        /**
         * 配套
         */
        //配套 -----------------住宅、商住、其他 182
        $data['zsq_matching'] = SystemType::storageRedis(182);

        //配套 -----------------写字楼、写厂 302
        $data['xx_matching'] = SystemType::storageRedis(302);

        //配套 -----------------厂房、仓库、地皮 321
        $data['ccd_matching'] = SystemType::storageRedis(321);

        //配套 -----------------车位 389
        $data['c_matching'] = SystemType::storageRedis(389);
        /**
         * 行业
         */
        //行业 -----------------商铺、铺厂、网点 261
        $data['spw_industryone'] = SystemType::storageRedis(261);
        /**
         * 家具
         */
        //家具 -----------------住宅、商住、其他  188
        $data['zsq_furniture'] = SystemType::storageRedis(188);
        /**
         * 厕所
         */
        //厕所 -----------------商铺、铺厂、网点  269
        $data['zsq_wc'] = SystemType::storageRedis(269);

        //厕所 -----------------写字楼、写厂306
        $data['xx_wc'] = SystemType::storageRedis(306);
        /**
         * 宿舍
         */
        //宿舍 -----------------厂房、仓库、地皮 326
        $data['ccd_dormroomthree'] = SystemType::storageRedis(326);

        //宿舍 -----------------车位 326
        $data['c_dormroomthree'] = SystemType::storageRedis(326);
        /**
         * 家电
         */
        //家电  -----------------住宅、商住、其他  196
        $data['zsq_homeappliance'] = SystemType::storageRedis(196);

        /**
         * 地段
         */
        //地段 -----------------商铺、铺厂、网点  272
        $data['zsq_lotone'] = SystemType::storageRedis(272);

        /**
         * 空调
         */
        //空调 -----------------写字楼、写厂309
        $data['xx_airtwo'] = SystemType::storageRedis(309);

        /**
         * 食堂
         */
        //食堂 -----------------厂房、仓库、地皮 339
        $data['ccd_canteenthree'] = SystemType::storageRedis(339);

        //食堂 -----------------车位 339
        $data['c_canteenthree'] = SystemType::storageRedis(339);
        return $this->success('ok', $data);
    }

    //获取房源所有跟进列表
    public function getAllFollow(Request $request)
    {
        $param = $request->all();
        $where = [];
        //跟进  开始时间
        if ($request->input('start_time')) {
            $where[] = ['f_created_at', '>=', strtotime($param['start_time'].' 00:00:00')];
        } else {
            $where[] = ['f_created_at', '>=', strtotime(date('Y-m-d',strtotime('-3 month')).' 00:00:00')];
        }
        //跟进结束时间
        if ($request->input('end_time')) {
            $where[] = ['f_created_at', '<=', strtotime($param['end_time'].' 23:59:59')];
        } else {
            $where[] = ['f_created_at', '<=', time()];
        }
        //类型  全部传空   跟进员工传1    房源归属人2
        if (!$request->input('people_type') || $request->input('people_type') == 1) {
            //部门ID
            if ($request->input('department_id')) {
                $where[] = ['f_department_id',  $request->input('department_id')];
            }else{
                $where[] = ['f_department_id',Auth::user()['u_d_id']];
            }
            //跟进人ID
            if ($request->input('u_id')) {
                $where[] = ['f_user_id',  $request->input('u_id')];
            }elseif (!$request->input('department_id') && !$request->input('u_id')){
                $where[] = ['f_user_id',Auth::user()['u_id']];
            }
        }
        //房源归属人2
        if ($request->input('people_type') == 2) {
            //部门ID
            if ($request->input('department_id')) {
                $where[] = ['r_d_id',  $request->input('department_id')];
            }else{
                $where[] = ['r_d_id',Auth::user()['u_d_id']];
            }
            //跟进人ID
            if ($request->input('u_id')) {
                $where[] = ['source_uid',  $request->input('u_id')];
            }elseif (!$request->input('department_id') && !$request->input('u_id')){
                $where[] = ['source_uid',Auth::user()['u_id']];
            }
        }

        //交易 全部 ==空 ， 出售 == 1  ， 出租  == 2，   租售  == 3
        // //   房源  出售 93    出租 94    租售 95
        if ($request->input('trading_type') == 1) {
            $where[] = ['trading_type',  93];
        } elseif ($request->input('trading_type') == 2) {
            $where[] = ['trading_type',  94];
        } elseif ($request->input('trading_type') == 3) {
            $where[] = ['trading_type',  95];
        }

        //跟进方式
        if ($request->input('f_follow_up_way')) {
            $where[] = ['f_follow_up_way',  $request->input('f_follow_up_way')];
        }

        //关键词智能搜索
        $keywords = '';
        if ($request->input('keywords')){
            //跟进的内容    房源的编号  业主姓名   业主电话
            $keywords = trim($request->input('keywords'));
        }
        $roomFollow = new RoomFollow();
        $list = $roomFollow->listFollow(env('PAGE_LIMIT_ADMIN'), $where, $keywords);

        if (!$list) {
            $data['start'] = date('Y-m-d',strtotime('-3 month'));
            $data['end']  = date('Y-m-d',time());
            return $this->error(Error::NULL_DATA,$data);
        }
        $start = date('Y-m-d',strtotime('-3 month'));
        $end = date('Y-m-d',time());
        return $this->success('ok', $list, $start, $end);

    }


    //验证房源业主的手机号
    public function verificationPhone(Request $request,RoomInfo $roomInfo)
    {
        $params = $request->except('token');
        $validator =  RoomInfoVail::verificationPhone($params);
        if (!$validator) {
            //参数不完整
            return $this->error(Error::PARAM_MISSING);
        }
        $id = 0;
        if ($request->input('id')) { //添加的时候没有房源的ID   修改的时候有房源ID
            $id = $request->input('id');
        }
        $data = $roomInfo->verificationPhone($params['owner_phone'], $id);
        if (!$data) {
            return $this->error(Error::CHECK_HOUSE);
        }
        return $this->success('ok', $data);
    }

    //房客源提醒默认数据
    public function RoomCustomerDefaultData(RoomInfo $roomInfo){
        $Auth =  Auth::user();
        $data['time'] = date('Y-m-d H:i:s',time());
//        $data['userName'] = $roomInfo->getUserName($Auth['u_id']);
        $data['userName'] = $Auth['u_username'];
        $data['userId'] = $Auth['u_id'];
        return $this->success('ok', $data);
    }

    public function UploadFiles(Request $request,RoomInfo $roomInfo)
    {
        $rid = $request->input('r_id');//房源ID
        $Auth =  Auth::user();
        $pathPefix = $Auth['u_b_id'].$Auth['u_d_id'].$Auth['u_id'].$rid;//路径部分前缀
        $files = $request->file('files');
        $wate = $request->input('wate');
        $imgArray = [];
        foreach($files as $key=>$value) {
            if (!$value->isValid()) {
                //文件不合法
                return $this->error(Error::FILE_ERROR);
            }
            $suffixname = $value->getClientOriginalExtension();
            if (!in_array($suffixname, $this->arr)) {
                return $this->error(Error::UPLOAD_SUFFIX_ERROR);
            }
            if($value->getClientSize() > $this->size){
                return $this->error(Error::PICTURE_LARGE);
            }
        }

        foreach($files as $key=>$value) {
            if($wate == 1){
                //添加水印操作
                $position = $request->input('position');
                $filePath = $roomInfo->ImgWatermark($value,$rid,$key,$position);
            }else{
                //不添加水印
                $filePath = $value->getRealPath();
            }
            //上传七牛云的文件名称
            $imgname = md5(uniqid());
            $nameHost = $pathPefix.$key.date('YmdHis', time()) . $imgname . '.' . $suffixname;
            $auth = new qiniuAuth(env('QINIU_ACCESSKEY'), env('QINIU_SECRETKEY'));
            $token = $auth->uploadToken(env('QINIU_BUCKET'));
            $uploadMgr = new UploadManager();
            $temp_arr = [
                'color' => 2
            ];
            list($ret, $err) = $uploadMgr->putFile($token, $nameHost, $filePath, $temp_arr);
//            dd($uploadMgr->putFile($token, $nameHost, $filePath, $temp_arr));
            if ($err !== null) {
                //上传七牛云存储失败
                return $this->error(Error::UPLOAD_ERROR);
            } else {
                unlink($filePath);
                //上传成功 返回图片路径
                $data = [
                    'preview_url' => env('QINIU_DOMAIN') . $ret['key'],
                    'add_url' => $ret['key']
                ];
                array_push($imgArray, env('QINIU_DOMAIN') . $ret['key']);
            }
        }
        $roomImgId = $roomInfo->addRoomImg($imgArray, $rid);
        if (!$roomImgId) {
            return $this->error(Error::UPLOAD_ERROR);
        }
        return $this->success('ok', $imgArray);
    }



    //图片列表
    public function ImagesLists(Request $request,RoomInfo $roomInfo){
        if(!$request->input('id')){
            return $this->error(Error::PARAM_MISSING);
        }
        $list = $roomInfo->ImagesLists($request->input('id'));
        return $this->success('ok',$list);
    }

    //删除图片
    public function delimg(Request $request,RoomInfo $roomInfo){

        if(!$riu_id = $request->input('riu_id')){
            return $this->error(Error::PARAM_MISSING);
        }

        if($roomInfo->delImages($riu_id)){
             return $this->success('ok', '操作成功！');
        }else{
            return $this->error(Error::OPERATION_ERROR);
        }

    }


    /**
     *APP端 房源 单图上传
     */
    public function UploadPic(Request $request,RoomInfo $roomInfo)
    {
        $rid = $request->input('r_id');//房源ID
        $apptoken = $request->input('apptoken');
        $data = explode(',', Redis::get($apptoken));
        $uid = $data[0].$data[2].$data[3];
        $files = $request->file('files');
        move_uploaded_file($files->getRealPath(), 'E:/wamp/www/fangchan/public/a.jpg');
        //上传七牛云的文件名称
        $imgname = md5(uniqid());
        $nameHost = $uid.$rid.date('YmdHis', time()) . $imgname . '.png';

        $auth = new qiniuAuth(env('QINIU_ACCESSKEY'), env('QINIU_SECRETKEY'));
        $token = $auth->uploadToken(env('QINIU_BUCKET'));
        $uploadMgr = new UploadManager();
        $temp_arr = [
            'color' => 2
        ];
        list($ret, $err) = $uploadMgr->putFile($token, $nameHost, 'E:/wamp/www/fangchan/public/a.jpg', $temp_arr);
        $imgArray = [];
        if ($err !== null) {
            //上传七牛云存储失败
            return $this->error(Error::UPLOAD_ERROR);
        } else {
            unlink('E:/wamp/www/fangchan/public/a.jpg');
            //上传成功 返回图片路径
            $data = [
                'preview_url' => env('QINIU_DOMAIN') . $ret['key'],
                'add_url' => $ret['key']
            ];
            array_push($imgArray, env('QINIU_DOMAIN') . $ret['key']);
        }

        $roomImgId = $roomInfo->addRoomImg($imgArray, $rid);
        if (!$roomImgId) {
            return $this->error(Error::UPLOAD_ERROR);
        }
        return $this->success('ok', $imgArray);
    }
    /**
     * APP端多图上传
     */
    public function UploadImg(Request $request,RoomInfo $roomInfo)
    {
        $rid = $request->input('r_id');//房源ID
        $apptoken = $request->input('apptoken');
        $data = explode(',', Redis::get($apptoken));
        $pathPefix = $data[0].$data[2].$data[3].$rid;//路径部分前缀
        $firstName = $_FILES['files']['name'];
        $nameObj = $_FILES['files']['tmp_name'];
        $sizeArr = $_FILES['files']['size'];
        $dir = iconv("UTF-8", "GBK", "uploads/img");
        if (!file_exists($dir)){
            mkdir ($dir,0777,true);
        }
        $imgArray = [];
        for ($i =0; $i < count($firstName); $i++) {
            if ($firstName[$i] != ''){
                $nameArr = explode('.', $firstName[$i]);
                $lastName = end($nameArr);
                if($sizeArr[$i] > $this->size){
                    return $this->error(Error::PICTURE_LARGE);
                }
                if (in_array($lastName, $this->arr)) {
                    $nameHost =  $pathPefix.$i.date('YmdHis', time()) . md5(uniqid()) .'.'. $lastName;
                    $saveName = $_SERVER['DOCUMENT_ROOT'].'/uploads/img/'.$nameHost;
                    move_uploaded_file($nameObj[$i], $saveName);
                    //上传图片到七牛云
                    $auth = new qiniuAuth(env('QINIU_ACCESSKEY'), env('QINIU_SECRETKEY'));
                    $token = $auth->uploadToken(env('QINIU_BUCKET'));
                    $uploadMgr = new UploadManager();
                    $temp_arr = [
                        'color' => 2
                    ];
                    list($ret, $err) = $uploadMgr->putFile($token, $nameHost, $saveName, $temp_arr);
                    if ($err !== null) {
                        //上传七牛云存储失败
                        return $this->error(Error::UPLOAD_ERROR);
                    } else {
                        unlink($saveName);
                        //上传成功 返回图片路径
                        $data = [
                            'preview_url' => env('QINIU_DOMAIN') . $ret['key'],
                            'add_url' => $ret['key']
                        ];
                        array_push($imgArray, env('QINIU_DOMAIN') . $ret['key']);
                    }
                } else {
                        return $this->error(Error::UPLOAD_SUFFIX_ERROR);
                }
            }
        }
        $roomImgId = $roomInfo->addRoomImg($imgArray, $rid);
        if (!$roomImgId) {
            return $this->error(Error::UPLOAD_ERROR);
        }
//        return $this->success('ok', $imgArray);
        return $this->success('ok', '上传成功！');
    }



}